/**
 * 管理机
 */
import "reflect-metadata";
/**
 * 引入公共文件
 */
import "../common";
/**
 * 管理机的主要职责是 管理本脚本下的所有任务
 * 1. 管理UI任务
 * 2. 管理脚本任务
 * 3. 务必轻量
 */
import { container as injector } from 'tsyringe'
import { Timer } from "../autox/timer";
import { Task } from "../autox/task";
import { kwai, $, toSecond } from '../utils';
import { sendToWebsocket } from "../utils/send";
import { getDeviceUuid } from "../tokens";
import { Sender } from "../autox/sender";
import dayjs from "dayjs";


const timer = injector.resolve(Timer)
const task = injector.resolve(Task)
const sender = injector.resolve(Sender)


timer.setInterval(() => { }, 1000 * 10)


events.on('exit', () => {
    sendToWebsocket({ type: 'TAKE_RED_PACKET_FINISH', payload: { pkg: $.PACKAGES["com.smile.gifmaker"] } })
    injector.dispose()
})

function yj() {
    let count: number = 0;
    try {
        const t = task.start(() => {
            kwai.openAndJoinVideoRoom()
            while (true) {
                try {
                    count += 1;
                    kwai.autoLookVideo()
                    toastLog(`正在去下一条视频，总共看了${count}个视频`)
                } catch (e) {
                    toastLog(e.message)
                } finally {
                    $.swipeUp()
                }
            }
        });
        t.join(random(5 * 60 * 1000, 8 * 60 * 1000))
        t.interrupt()
    } catch (e) {
        toastLog(e.message)
    }
}


sender.on('JOIN_RED_ROOM', (payload: any) => {
    toastLog(`找到一个直播间：` + payload.name)
    home();
    sleep(2000);
    setClip(payload.link);
    sleep(2000);
    const hour = dayjs().get('hour')
    if (hour % 2 === 0) {
        app.launchPackage($.PACKAGES["com.smile.gifmaker"])
    } else {
        app.launchPackage($.PACKAGES["com.kuaishou.nebula"])
    }
    sleep(2000)
    getRedRoom()
    takeRedPacket()
})
let timeout: any;
function getRedRoom() {
    if (timeout) {
        clearTimeout(timeout)
    }
    timeout = setTimeout(() => {
        sendToWebsocket({ type: "GET_RED_ROOM", payload: { uuid: getDeviceUuid() } })
    }, 2 * 60 * 1000)
}

try {
    toastLog(`任务开始执行`)
    task.start(() => {
        sendToWebsocket({ type: "GET_RED_ROOM", payload: { uuid: getDeviceUuid() } })
        while (true) {
            try {
                checkRoomStatus()
            } catch (e) {
                toastLog(e.message)
            } finally {
            }
        }
    })
} catch (e) {
    toastLog(e.message)
}

export function takeRedPacket() {
    try {
        // id("live_activity_red_packet_display_text_view")
        selector().visibleToUser(true).idMatches(/.*?(live_red_packet_status_text|live_activity_red_packet_display_text_view)/).waitFor();
        const node = selector().visibleToUser(true).idMatches(/.*?(live_red_packet_status_text|live_activity_red_packet_display_text_view)/).findOne()
        const onlineText = selector().visibleToUser(true).idMatches(/.*?live_audience_count_text/).findOne()?.text() || `0`;
        const online = parseInt(onlineText)
        const second = toSecond(node.text())
        if (second <= 5) {
            sleep(5000)
            sendToWebsocket({ type: "GET_RED_ROOM", payload: { uuid: getDeviceUuid() } })
            throw new Error(`暂无红包`)
        }
        if (node) $.clickButton(node)
        sleep(3000)
        let redPacketInfo: any;
        try {
            redPacketInfo = kwai.getRedPacketInfoSimple()
        } catch (e) {
            throw new Error(`暂无红包`)
        }
        if (!redPacketInfo) {
            throw new Error(`无红包`)
        }
        const { maxCount, redPacketsList } = redPacketInfo;
        toastLog(`共有${redPacketsList.length}个红包，最大的是${maxCount}`)
        const list = redPacketsList.sort((a, b) => a.index - b.index)
        for (let index in list) {
            const redPacket = redPacketsList[index];
            const idx = redPacket.index + 1;
            selector().classNameMatches(/.*?android.widget.FrameLayout/).depth(2).visibleToUser(true).waitFor()
            const container = selector().classNameMatches(/.*?android.widget.FrameLayout/).depth(2).visibleToUser(true).findOne()
            if (idx === container?.drawingOrder()) {
                toastLog(`刚好是这个包，那就报名参加吧！${idx} ${container?.drawingOrder()}`)
                joinRedPacket(redPacket, online, idx)
            } else {
                toastLog(`不是这个包，滑一下吧！`)
                sleep(3000)
                const bounds = container.bounds()
                click(device.width - 50, bounds.centerY())
                sleep(3000)
                joinRedPacket(redPacket, online, idx)
                sleep(3000)
            }
        }
    } catch (e) {
        sleep(5000)
        toastLog(e.message)
    }
}

export function joinRedPacket(redPacket: any, online: number, idx: number) {
    // 快币包
    if (redPacket.type === 0) {
        // id("live_condition_leee_button_text")
        selector().idMatches(/.*?(live_condition_leee_button_text|action_view)/).visibleToUser(true).waitFor()
        const viewBtn = selector().idMatches(/.*?(live_condition_leee_button_text|action_view)/).visibleToUser(true).findOne(3000);
        $.clickButton(viewBtn)
        sleep(4000)
        toastLog(`成功参加主播的快币包`)
    }
    // 粉丝
    if (redPacket.type === 1) {
        try {
            const v = (redPacket.total / online) * redPacket.count;
            if (v > 1.5) {
                selector().idMatches(/.*?(live_condition_leee_button_text|action_view)/).visibleToUser(true).waitFor()
                const viewBtn = selector().idMatches(/.*?(live_condition_leee_button_text|action_view)/).visibleToUser(true).findOne()
                $.clickButton(viewBtn)
                sleep(4000)
                // id("live_audience_fans_group_join_fans_group_button")
                selector().idMatches(/.*?live_audience_fans_group_join_fans_group_button/).visibleToUser(true).waitFor()
                const joinBtn = selector().idMatches(/.*?live_audience_fans_group_join_fans_group_button/).visibleToUser(true).findOne()
                $.clickButton(joinBtn)
                sleep(random(1000, 3000))
                toastLog(`成功参加粉丝包，收益率为${v}`)
                back();
                sleep(random(1000, 3000))
            }
        } catch (e) { }
    }
    // 口令包
    if (redPacket.type === 2) {
        try {
            selector().idMatches(/.*?(live_condition_leee_button_text|action_view)/).visibleToUser(true).waitFor()
            const viewBtn = selector().idMatches(/.*?(live_condition_leee_button_text|action_view)/).visibleToUser(true).findOne(3000);
            // const viewBtn = selector().idMatches(/.*?(live_condition_leee_button_text|action_view)/).visibleToUser(true).findOne(3000)
            $.clickButton(viewBtn)
            sleep(random(1000, 2000))
            selector().textContains('发送').visibleToUser(true).waitFor()
            $.clickButton($.getVisibleElementByText('发送'))
            toastLog(`成功参加主播的口令包`)
            sleep(random(1000, 3000))
        } catch (e) { }
    }
    // 限时抢
    if (redPacket.type === 3) {
        sleep(4000)
    }
    // 分享包
    if (redPacket.type === 4) {
        try {
            selector().idMatches(/.*?(live_condition_leee_button_text|action_view)/).visibleToUser(true).waitFor()
            const viewBtn = selector().idMatches(/.*?(live_condition_leee_button_text|action_view)/).visibleToUser(true).findOne(3000);
            $.clickButton(viewBtn)
            sleep(random(1000, 3000))
            selector().textMatches(/.*?复制连接.*?/).visibleToUser(true).waitFor()
            const copyLink = selector().textMatches(/.*?复制连接.*?/).visibleToUser(true).findOne(3000)
            $.clickButton(copyLink)
            sleep(random(1000, 3000))
            const link = getClip()
            sendToWebsocket({ type: 'TAKE_RED_PACKET_TASK_SHARE', payload: { link: link } })
            toastLog(`成功参加主播的分享包 每个${redPacket.count}开闭 总共${redPacket.total}个`)
        } catch (e) { }
    }
}
function checkParent(node: UiObject, fn: (p: UiObject) => boolean) {
    if (fn(node)) return true;
    if (node.parent()) return this.getParent(node.parent())
    return false;
}
declare const getClip: any;
export function checkRoomStatus() {
    const joinRedPacket = selector().textMatches(/进入直播间|退出直播间|退出/).findOne(1000 * 2)
    if (joinRedPacket) {
        sleep(2000)
        $.clickButton(joinRedPacket)
        sleep(2000)
        return;
    }
    const texts = kwai.getLiveRoomText()
    const text = texts.join(' ')
    if (text.includes('免费票次日6点清空')) {
        // todo 点掉免费的票
        return;
    }
    if (text.includes('立即关注') || (text.includes('关注') && text.includes('主页'))) {
        back();
        return;
    }
    const failResult = text.match(/.*(很遗憾，本次未中奖|红包溜走了|直播已结束).*/)
    if (failResult && failResult.length > 0) {
        toastLog(`很遗憾，本次没有中奖`)
        sleep(5000)
        back();
        sleep(3000);
        $.clickButton($.getVisibleElementById('live_close'))
        const ele = $.getVisibleElementByText('退出直播间')
        if (ele) {
            $.clickButton(ele)
            sleep(3000)
        }
        sendToWebsocket({ type: "GET_RED_ROOM", payload: { uuid: getDeviceUuid() } })
    }
    const successResult = text.match(/.*\s仅需\d快币/)
    if (successResult && successResult.length > 0) {
        toastLog(`恭喜您中奖了`)
        sleep(5000)
        back();
        sleep(3000);
        $.clickButton($.getVisibleElementById('live_close'))
        const ele = $.getVisibleElementByText('退出直播间')
        if (ele) {
            $.clickButton(ele)
            sleep(3000)
        }
        sendToWebsocket({ type: "GET_RED_ROOM", payload: { uuid: getDeviceUuid() } })
    }
    const waitResults = text.match(/.*\s(.*?)后开奖/)
    if (waitResults && waitResults.length > 1) {
        const [, time] = waitResults;
        return;
    }
    const kaiResults = text.match(/.*?正在开奖/)
    if (kaiResults && kaiResults.length > 0) {
        log(`正在开奖`)
        return;
    }

}